<?php
/**
 * Create by 11li
 * Date 2020/3/30
 * Time 22:37
 *
 */

namespace app\common\service\v2;
use app\admin\model\User as UserModel;
use app\common\model\AgentShip;
use app\common\model\AgentShop;
use app\common\model\AgentStock;
use app\common\model\AgentStockRecord;
use app\common\model\ChainFunds;
use app\common\model\Commission;
use \app\common\model\Order as OrderModel;
use app\common\model\OrderGoods;
use think\Db;
use think\Exception;
use think\exception\DbException;

class OrderService
{
	public static function getCenterOrder($agentId, $status = OrderModel::STATUS_WAIT_SHIPPING, $page = 1)
	{
		$where = [
			'center_id' => $agentId,
			'is_delete' => 0,
			'status' => $status,
			'order_type' => OrderModel::TYPE_NORMAL,
			'center_shipping' => 1
		];
		
		$model = new OrderModel();
		
		$count = $model->where($where)->count();
		$orders = $model->where($where)
			->order(['update_time' => 'desc'])
			->page($page)
			->select();
		
		$list = [];
		if($orders) {
			foreach ($orders as $item) {
				$item = $item->toArray();
				$goods = Db::name('orderGoods')
					->where(['order_id' => $item['id']])
					->select();
				foreach ($goods as &$good) {
					$good['goods_info'] = json_decode($good['goods_info'], true);
				}
				
				$item['goods']  = $goods;
				$list[] = $item;
			}
		}
		
		return [
			'total' => $count,
			'list' => $list
		];
	}
	
	public static function sendGoods($agentId, $orderId, $shippingName, $shippingNo, $userId)
	{
		$where = [
			'center_id' => $agentId,
			'is_delete' => 0,
			'order_type' => OrderModel::TYPE_NORMAL,
			'center_shipping' => 1,
			'id' => $orderId
		];
		
		$model = new OrderModel();
		
		$order = $model->where($where)->find();
		if(!$order) {
			throw new Exception('该订单存在');
		}
		
		if($order['status'] != OrderModel::STATUS_WAIT_SHIPPING) {
			throw new Exception('非待发货订单');
		}
		
		$orderGoods = OrderGoods::get(['order_id' => $orderId]);
		$goodsId = $orderGoods['goods_id'];
		$goodsInfo = json_decode($orderGoods['goods_info'], true);
		$specId = $goodsInfo['spec_id'];
		$stockNumber = StockService::getAgentGoodsIdStock($agentId, $goodsId, $specId);
		if($stockNumber < $orderGoods['number']) {
			throw new Exception('库存不足');
		}
		
		$model->startTrans();
		try {
			// 添加物流信息
			$shippingRes = ShippingService::addRecord($orderId, $shippingName, $shippingNo, $agentId);
			if(!$shippingRes) {
				throw new Exception('添加物流信息出错');
			}
			
			// 更改订单状态
			$orderRes = $model->save([
				'status' => OrderModel::STATUS_WAIT_SIGN,
				'shipping_status' => OrderModel::SHIPPING_STATUS_WAIT,
				'shipping_time' => time(),
			], ['id' => $orderId]);
			if(!$orderRes) {
				throw new Exception('更改订单状态出错');
			}
			
			$number = $order['number'];
			$orderGoods = OrderGoods::get(['order_id' => $orderId]);
			// 添加待返利核销佣金
			self::setDestoryCommission($goodsId, $orderGoods['id'], $agentId, $number, $order);
			
			$agent = AgentShop::get($agentId);
			// 减库存
			$stockModel = new AgentStock();
			$stockRes = $stockModel->add($agent['user_id'], $agentId, $goodsId, $specId, -$number);
			if(!$stockRes) {
				throw new Exception('减少库存出错');
			}
			
			//添加库存记录
			$recordModel = new AgentStockRecord();
			$recordRes = $recordModel->addRecord($agent['user_id'], $goodsId, $specId, $recordModel::TYPE_DESTRUCT, $number, '订单取货核销');
			if(!$recordRes) {
				throw new Exception('添加库存记录出错');
			}
			
			//添加核销记录
			$shipModle = new AgentShip();
			$shopRes = $shipModle->addRecore($order['id'], $agent['id'], $goodsId, $specId, $number, $order['code']);
			if(!$shopRes) {
				throw new Exception('添加核销记录出错');
			}
			
			$model->commit();
			return true;
		} catch (Exception $e) {
			$model->rollback();
			throw new Exception($e->getMessage());
		}
	}
	
	
	/**
	 * @param $goodsId 商品ID
	 * @param $orderGoodsId 订单详情ID
	 * @param $agentId 代理ID
	 * @param $number 数量
	 * @param $order 订单
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws DbException
	 */
	public static function setDestoryCommission($goodsId, $orderGoodsId, $agentId, $number, $order)
	{
		$agent = AgentShop::get($agentId);
		
		//获取设置信息(优先是单独设置的规则）
		$setting = Db::name('goodsRule')->where(['goods_id' => $goodsId])->find();
		//其它地区核销规则
		if($order['area'] == UserModel::AREA_OTHER) {
			//发核销佣金, 核销点有5元，核销点上级提货点有5元，提货点的上级提货点算自己
			if(!$setting) {
				$setting = Db::name('setting')->find();
			}
			if($setting && ($setting['shop_ship_amount'] > 0 || $setting['warehouse_amount'] > 0)) {
				$commissionModel = new Commission();
				//场景店,自己5元，归属提货点5元
				if($agent['role'] == UserModel::LEVEL_SHOP) {
					
					if($setting['shop_ship_amount'] > 0) {
						$shopRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'], $goodsId, $orderGoodsId, $setting['shop_ship_amount'] * $number, '场景店核销奖励', $commissionModel::TYPE_GOODS);
						
						if(!$shopRes) {
							throw new Exception('添加场景店核销奖励出错');
						}
					}
					
					if($setting['warehouse_amount'] > 0 && $agent['warehouse_id']) {
						$warehouse = Db::name('agentShop')->find($agent['warehouse_id']);
						if($warehouse && $warehouse['status'] == AgentShop::STATUS_Y) {
							$msg = '提货点下级核销奖励';
							$warehouseCommission = $setting['warehouse_amount'] * $number;
							$warehouseUserId = $warehouse['user_id'];
							//是连锁店，钱给上给
							if($warehouse['chain_user_id']) {
								$warehouseUserId = $warehouse['chain_user_id'];
								$fundsRes = ChainFunds::addRecord($warehouseUserId, $warehouse['id'], $order['id'], $warehouseCommission, ChainFunds::TYPE_DESTORY);
								if(!$fundsRes) {
									throw new Exception('添加连锁佣金记录出错');
								}
								$msg = '连锁店下级提货点核销奖励';
							}
							
							$warehouseRes = $commissionModel->rebate($warehouseUserId, $order['user_id'], $order['id'], $goodsId, $orderGoodsId, $warehouseCommission, $msg, $commissionModel::TYPE_STOCK);
							if(!$warehouseRes) {
								throw new Exception('添加提货点奖励出错');
							}
						}
					}
				} else if($agent['role'] == UserModel::LEVEL_WAREHOUSE) {
					//销售是场景店，自己拿了核销和核销上级的钱
					$msg = '提货点核销奖励';
					$warehouse = $agent;
					//场景店
					if($warehouse && $warehouse['role'] == UserModel::LEVEL_WAREHOUSE) {
						$warehouseCommission = ($setting['warehouse_amount'] + $setting['shop_ship_amount']) * $number;
						$warehouseUserId = $warehouse['user_id'];
						if($warehouse['chain_user_id']) {
							$warehouseUserId = $warehouse['chain_user_id'];
							$fundsRes = ChainFunds::addRecord($warehouseUserId, $warehouse['id'], $order['id'], $warehouseCommission, ChainFunds::TYPE_DESTORY);
							if(!$fundsRes) {
								throw new Exception('添加连锁佣金记录出错');
							}
							$msg = '连锁店下级提货点核销奖励';
						}
						
						$warehouseRes = $commissionModel->rebate($warehouseUserId, $order['user_id'], $order['id'], $goodsId, $orderGoodsId, $warehouseCommission, $msg, $commissionModel::TYPE_GOODS);
						if(!$warehouseRes) {
							throw new Exception('添加提货点奖励出错');
						}
						
					}
				}
				
				
			}
		} else {
			$globalSetting = Db::name('ruleSz')->find();
			//核销佣金
			$destoryCommission = $setting ? $setting['sz_destory_amount'] : $globalSetting['destory_amount'];
			//火爆街铺货佣金
			$centerStockCommission = $setting ? $setting['sz_parent_amount'] : $globalSetting['parent_amount'];
			
			//提货点铺货佣金
			$warehouseStockCommission = 0;
			
			//查找是否提货点核销自己的推广订单
			if($order['recommend_user_id'] == $agent['user_id'] && $agent['role'] == UserModel::LEVEL_WAREHOUSE) {
				$warehouseStockCommission = $setting ? $setting['warehouse_sale'] : $globalSetting['warehouse_sale'];
				$centerStockCommission = $setting ? $setting['warehouse_parent'] : $globalSetting['warehouse_parent'];
			}
			
			$centerAgentId = $agent['role'] == UserModel::LEVEL_CENTER ? $agent['id'] : $agent['center_id'];
			
			$commissionModel = new Commission();
			//添加核销佣金
			if($destoryCommission > 0) {
				$destoryCommission = $destoryCommission * $number;
				$destoryRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'], $goodsId, $orderGoodsId, $destoryCommission, '核销奖励(深圳)', $commissionModel::TYPE_GOODS);
				if(!$destoryRes) {
					throw new Exception('添加核销奖励出错');
				}
			}
			
			//添加火爆街
			if($centerStockCommission > 0 && $centerAgentId) {
				$centerAgent = AgentShop::get(['id' => $centerAgentId, 'status' => AgentShop::STATUS_Y]);
				if($centerAgent) {
					$centerStockCommission = $centerStockCommission * $number;
					$centerRes = $commissionModel->rebate($centerAgent['user_id'], $order['user_id'], $order['id'], $goodsId, $orderGoodsId, $centerStockCommission, '火爆街铺货佣金(深圳)', $commissionModel::TYPE_STOCK);
					if(!$centerRes) {
						throw new Exception('添加火爆街铺货佣金出错');
					}
				}
			}
			
			//场景店核销别人的有2元铺货佣金
			if($warehouseStockCommission > 0) {
				$warehouseStockCommission = $warehouseStockCommission * $number;
				$warehouseRes = $commissionModel->rebate($agent['user_id'], $order['user_id'], $order['id'], $goodsId, $orderGoodsId, $warehouseStockCommission, '提货点铺货佣金(深圳)', $commissionModel::TYPE_STOCK);
				if(!$warehouseRes) {
					throw new Exception('添加提货点铺货佣金出错');
				}
			}
			
		}
	}
}